package com.tanhua.dubbo.server.api;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Service;
import com.mongodb.client.result.DeleteResult;
import com.tanhua.dubbo.server.enums.IdType;
import com.tanhua.dubbo.server.pojo.FollowUser;
import com.tanhua.dubbo.server.pojo.Video;
import com.tanhua.dubbo.server.service.IdService;
import com.tanhua.dubbo.server.vo.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.ArrayList;
import java.util.List;

/**
 * 小视频实现类
 */
@Service(version = "1.0.0")
@Slf4j
public class VideoApiImpl implements VideoApi {
    @Autowired
    private IdService idService;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    private static final String VIDEO_FOLLOW_USER_KEY_PREFIX = "VIDEO_FOLLOW_USER_";

    /**
     * 保存小视频
     *
     * @param video 小视频对象
     * @return 保存成功后，返回视频id
     */
    @Override
    public String saveVideo(Video video) {
        // 校验传入参数是否齐全：上传视频用户id、视频封面文件、视频文件
        if (!ObjectUtil.isAllNotEmpty(video.getUserId(), video.getPicUrl(), video.getVideoUrl())) {
            return null;
        }

        try {
            // 补充信息
            video.setId(ObjectId.get()); // 主键id
            video.setVid(this.idService.createId(IdType.VIDEO)); // 自增长id（用于系统推荐）
            video.setCreated(System.currentTimeMillis()); // 创建时间


            // 保存到mongodb中
            this.mongoTemplate.save(video);

            return video.getId().toHexString();
        } catch (Exception e) {
            log.error("小视频发布失败~ video = " + video, e);
        }

        return null;
    }

    /**
     * 分页查询小视频列表
     * 条件：按照时间倒序排序
     *
     * @param userId   用户id
     * @param page     当前页
     * @param pageSize 页大小
     * @return
     */
    @Override
    public PageInfo<Video> queryVideoList(Long userId, Integer page, Integer pageSize) {
        /* 分析：先查询推荐列表，当推荐列表没有或已查完后，查询系统默认中的列表 */
        PageInfo<Video> pageInfo = new PageInfo();
        pageInfo.setPageNum(page);
        pageInfo.setPageSize(pageSize);

        /* 设置分页参数 */
        String redisKey = "QUANZI_VIDEO_RECOMMEND_" + userId;
        String redisData = this.redisTemplate.opsForValue().get(redisKey);
        // 查询推荐列表总条，以便后续查看默认列表
        int recommendCount = 0;
        // 创建存放vid的集合
        List<Long> vidList = new ArrayList<>();
        if (StrUtil.isNotEmpty(redisData)) {
            // 获得所有推荐视频的自增长id
            String[] vidArr = StrUtil.splitToArray(redisData, ",");

            // 手动分页
            int[] startEnd = PageUtil.transToStartEnd(page - 1, pageSize);
            int startIndex = startEnd[0]; //开始
            int endIndex = Math.min(startEnd[1], vidArr.length); //结束

            for (int i = startIndex; i < endIndex; i++) {
                vidList.add(Long.valueOf(vidArr[i]));
            }
            recommendCount = vidArr.length;
        }
        // 计算出推荐列表总页数
        int recommendTotalPage = PageUtil.totalPage(recommendCount, pageSize);

        List<Video> videoList = null;
        if (CollUtil.isNotEmpty(vidList)) {
            /* 查询推荐列表 */
            // 推荐vid有值，查询推荐列表
            Query query = Query.query(Criteria.where("vid").in(vidList));
            videoList = this.mongoTemplate.find(query, Video.class);
        } else {
            /* 查询系统默认列表 */
            // 推荐vid无值，查询默认列表
            PageRequest pageable = PageRequest.of(page - 1 - recommendTotalPage,
                    pageSize, Sort.by(Sort.Order.desc("created")));
            Query query = new Query().with(pageable);
            videoList = this.mongoTemplate.find(query, Video.class);
        }

        /* 分装数据并返回 */
        pageInfo.setRecords(videoList);
        return pageInfo;
    }

    /**
     * 关注用户
     *
     * @param userId       当前用户
     * @param followUserId 关注的目标用户
     * @return
     */
    public Boolean followUser(Long userId, Long followUserId) {
        if (!ObjectUtil.isAllNotEmpty(userId, followUserId)) {
            return false;
        }
        try {
            //需要将⽤户的关注列表，保存到redis中，⽅便后续的查询
            //使⽤redis的hash结构
            if (this.isFollowUser(userId, followUserId)) {
                return false;
            }

            FollowUser followUser = new FollowUser();
            followUser.setId(ObjectId.get());
            followUser.setUserId(userId);
            followUser.setFollowUserId(followUserId);
            followUser.setCreated(System.currentTimeMillis());
            this.mongoTemplate.save(followUser);

            //保存数据到redis
            String redisKey = this.getVideoFollowUserKey(userId);
            String hashKey = String.valueOf(followUserId);
            this.redisTemplate.opsForHash().put(redisKey, hashKey, "1");

            return true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    /**
     * 取消关注用户
     *
     * @param userId       当前用户
     * @param followUserId 关注的目标用户
     * @return
     */
    public Boolean disFollowUser(Long userId, Long followUserId) {
        if (!ObjectUtil.isAllNotEmpty(userId, followUserId)) {
            return false;
        }

        if (!this.isFollowUser(userId, followUserId)) {
            return false;
        }

        // 取消关注，删除视频即可
        Query query = Query.query(Criteria.where("userId").is(userId)
                .and("followUserId").is(followUserId)
        );
        DeleteResult result = this.mongoTemplate.remove(query, FollowUser.class);

        if (result.getDeletedCount() > 0) {
            //同时删除redis中的数据
            String redisKey = this.getVideoFollowUserKey(userId);
            String hashKey = String.valueOf(followUserId);
            this.redisTemplate.opsForHash().delete(redisKey, hashKey);
            return true;
        }

        return false;
    }

    /**
     * 查询用户是否关注某个用户
     *
     * @param userId       当前用户
     * @param followUserId 关注的目标用户
     * @return
     */
    public Boolean isFollowUser(Long userId, Long followUserId) {
        String redisKey = this.getVideoFollowUserKey(userId);
        String hashKey = String.valueOf(followUserId);
        return this.redisTemplate.opsForHash().hasKey(redisKey, hashKey);
    }

    private String getVideoFollowUserKey(Long userId) {
        return VIDEO_FOLLOW_USER_KEY_PREFIX + userId;
    }
}
